const app = getApp();
const api = require('../../../../ws_micro_shop/utils/api.js');
const { qyWXCheckSeesion } = require('../../../../common/utils/ws/ws-wxwork');
const { throttle } = require('../../../common/utils/util');
const { getIsRole } = require('../../../api/common');

Page({
  data: {
    showMore: false,
    showMoreGuide: false,
    studentInfo: {},
    basicInfo: [],
    labels: [],
    tabs: [
      {
        name: '客户动态',
        list: ['全部动态', '浏览', '购买', '购物车', '搜索'],
      },
      {
        name: '客户跟进',
        // list: ['全部跟进', '跟进记录', '编辑状态', '发券记录']
      },
    ],
    current: 0,
    subCurrent: 0,
    recordingInfo: [],
    buttons: ['留言', '添加跟进', '拨打电话'],
    isWXWork: app.isWXWork,
    page: 2,
    customerId: '', // 消费者id
    externalUserId: '', // 外部联系人id
    isData: false,
    // is_show_line: false,
    isShow: false,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '暂无',
    },
    imgUrl: app.imgUrl,
    from_openid:'',
    showLoad: true,
  },
  onLoad() {
    this.setData({
      isSaas: app.ws_micro_shop_globalData.isSaas,
      corpid: wx.getStorageSync('corpid')
    })
  },

  async onShow() {
    const { role: isAdmin = '' } = await getIsRole();

    const { id: customerId = '' } = this.options;
    if (app.isWXWork && !customerId) {
      this.getExternalCustomerInfo();
    } else {
      this.setData(
        {
          customerId,
          from_openid: app.ws_micro_shop_globalData.openid,
          role: app.ws_micro_shop_globalData.role,
          isAdmin,
        },
        () => {
          this.init();
        }

      );
    }
  },

  init() {
    this.getUserInfo();
    this.getLabels();
    this.getBasicInfo();
    this.getClues();
  },

  onNavigate:throttle(function(e) {
    const { url = '', ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  }),

  getUserInfo() {
    const { customerId: customer_id } = this.data;

    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.clue_user_detail,
      data: {
        customer_id,
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          const studentInfo = { ...res.data };

          this.setData({
            studentInfo,
            customerOpenid: studentInfo.wechat_open_id,
            externalUserId: studentInfo.external_userid,
            isShow: true,
          });
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  getBasicInfo() {
    const { customerId: customer_id } = this.data;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.clue_consume,
      data: {
        customer_id,
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          const resData = res.data;
          const basicInfo = [
            {
              name: '购买次数',
              content: resData.orderCount ? `${resData.orderCount}次` : '0次',
            },
            {
              name: '最近消费',
              content: resData.last,
            },
            {
              name: '累计消费',
              content: resData.total_sales
                ? `${resData.total_sales}元`
                : '0.00元',
            },
            {
              name: '余额',
              content: resData.money ? `${resData.money}元` : '0.00元',
            },
            {
              name: '积分',
              content: resData.integral || '0',
            },
            {
              name: '优惠券',
              content: resData.coupons ? `${resData.coupons}张` : '0张',
            },
          ];
          this.setData({
            basicInfo,
          });
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  getLabels() {
    const { customerId: customer_id } = this.data;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.clue_user_label,
      data: {
        customer_id,
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          const { list: labels = [] } = res.data;
          this.setData({
            labels,
          });
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  onTab(e) {
    const { index, currentname } = e.currentTarget.dataset;

    this.setData(
      {
        [currentname]: index,
        recordingInfo: [],
        subCurrent: currentname === 'current' ? 0 : index,
        isData: false,
        showLoad: true,
        page: 2
      },
      () => {
        this.getClues();
      }
    );
  },

  getClues() {
    const { customerId: customer_id, subCurrent: status, current } = this.data;
    let type = current + 1;

    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.clue_info,
      data: {
        customer_id,
        type: type,
        page: 1,
        status,
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          const { list: recordingInfo = [] } = res.data;
          this.setData({
            recordingInfo,
            isData: true,
          });
          if (this.data.recordingInfo.length < 1 && type === 1) {
            this.setData({
              'abnorData.text': '暂无客户动态',
            });
          } else if (this.data.recordingInfo.length < 1 && type === 2) {
            this.setData({
              'abnorData.text': '暂无客户跟进',
            });
          }
        }
      },
      complete: res => {
        wx.hideLoading();
      },
    });
  },

  onReachBottom() {
    let that = this;
    let {
      customerId: customer_id,
      subCurrent: status,
      page,
      current,
      recordingInfo: oldlist,
      showLoad,
    } = this.data;

    if(showLoad){
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.clue_info,
      data: {
        customer_id,
        type: current + 1,
        page: page,
        status,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let list = res.data.list;
          let newlist = [];
          if (list.length > 0) {
            newlist = that.checkDateText(oldlist, list);
            page += 1;
          } else {
            newlist = oldlist;
              that.setData({
                showLoad: false,
              });
          }
          that.setData({
            recordingInfo: newlist,
            page: page,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      complete: function() {},
    });
    }  
    
  },
  checkDateText(oldlist, list) {
    let oldlist_length = oldlist.length;
    if (oldlist[oldlist_length - 1][0].date === list[0][0].date) {
      oldlist[oldlist_length - 1].push.apply(oldlist[oldlist_length - 1], list[0]);
      function curtail(arr) {
        return arr.filter(function(ele,idx,arr){
            return idx !== 0;
        });
      }
      return oldlist.concat(curtail(list))
    } else {
      return oldlist.concat(list);
    }

  },

  onOperation(e) {
    const { index, currentname } = e.currentTarget.dataset;

    this.setData(
      {
        [currentname]: index,
      },
      () => {
        const { customerId: id } = this.data;
        if (index === 0) {
          if (app.isWXWork) {
            this.openChat();
          } else {
            this.toLeaveMessage();
          }
        } else if (index === 1) {
          let url = '/ws_micro_shop_guide/pages/record/record';
          app.util.navigateTo(url, { type: 'addFollow', id });
        } else {
          this.onTel();
        }
      }
    );
  },

  onTel() {
    const {
      studentInfo: { mobile: phoneNumber = '' },
    } = this.data;

    phoneNumber && wx.makePhoneCall({
              phoneNumber,
            });
  },

  toggeleMore() {
    this.setData({
      showMore: !this.data.showMore,
    });
  },
  toggeleMoreGuide() {
    this.setData({
      showMoreGuide: !this.data.showMoreGuide,
    });
  },

  editTags:throttle(function() {
    const { from_openid: openid = '', customerOpenid = '' } = this.data;
    app.util.navigateTo(
      `/common/component/universal-card/pages/customer-info/customer-tag?openid=${openid}&customerOpenid=${customerOpenid}`
    );
  }),

  getExternalCustomerInfo() {
    qyWXCheckSeesion({
      success: () => {
        wx.qy.getCurExternalContact({
          success: res => {
            const externalUserId = res.userId;
            this.setData(
              {
                externalUserId,
              },
              () => {
                this.getCustomerId();
              }
            );
          },
        });
      },
      fail: err => {
        console.log('企业微信登录失败', err);
      },
    });
  },

  getCustomerId() {
    const { externalUserId: external_userid = '' } = this.data;
    app.util.request({
      url: api.guide.get_external_userid,
      data: {
        external_userid,
      },
      success: res => {
        if (res.data && res.data.errno === 0 && res.data.data) {
          this.setData(
            {
              customerId: res.data.uid,
            },
            () => {
              this.init();
            }
          );
        }
      },
    });
  },

  openChat() {
    let that = this;
    qyWXCheckSeesion({
      success: () => {
        const { externalUserId } = that.data;
        if (externalUserId) {
          wx.qy.openEnterpriseChat({
            externalUserIds: externalUserId,
            groupName: '',
            success: () => {
              console.log('enterprise chat opened');
            },
            fail: (error) => {
              console.log('enterprise fail', error);
            }
          });
        } else {
          that.toLeaveMessage();
        }
      },
      fail: err => {
        console.log('企业微信登录失败', err);
      },
    });
  },

  toLeaveMessage() {
    const { from_openid, customerOpenid: to_openid = '', studentInfo } = this.data;
    const url = `/ws_micro_shop_guide/pages/message/detail/detail?from_openid=${from_openid}&to_openid=${to_openid}&name=${studentInfo.nickname || studentInfo.realname}`;
    app.util.navigateTo(url);
  }
});
